package org.shangrila.app.wechat.bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

import org.apache.taglibs.standard.lang.jstl.test.beans.PublicInterface2;
import org.shangrila.app.wechat.utils.WeChatUtil;
import org.shangrila.bme.eo.BmeAcception;
import org.shangrila.bme.eo.BmeContract;
import org.shangrila.bme.eo.BmePurchDetail;
import org.shangrila.bme.eo.BmePurchOrder;
import org.shangrila.bme.eo.BmeReceipt;
import org.shangrila.bme.mb.BmeWfmReceiptMB;
import org.shangrila.comm.dao.DbAccess;
import org.shangrila.wfm.eo.WfmNode;
import org.shangrila.wfm.eo.WfmTask;

import com.mysql.fabric.xmlrpc.base.Data;

@Named
@ApplicationScoped
public class WechatMessageUtils {
	
	public static final String PROCESS_WF_HTSH="wf_htsh"; 	//WFM流程
	public static final String PROCESS_WF_CGDD="wf_cgdd"; 	
	public static final String PROCESS_WF_FHD="wf_fhd"; 
	public static final String PROCESS_WF_YSDSH="wf_ysdsh"; 
	public static final String PROCESS_WF_HTBG="wf_htbgsq";
	
	private  static DbAccess db = new DbAccess();
	
	/**  
	 * <p>Title: findCurrentNode</p>  
	 * <p>Description: 通过当前任务名、当前流程获取当前节点</p>  
	 * @param taskName
	 * @param process
	 * @return  
	 */
	public static WfmNode findCurrentNode(WfmTask task) {
		
		StringBuilder nodeSql = 
				new StringBuilder("select m from WfmNode m ");
		StringBuilder nodeWhere=new StringBuilder("where m.name=?1 and m.wfmProcess=?2");
		List<Object> params=new ArrayList<>();
		params.add(0,task.getTaskName());
		params.add(1,task.getWfmProcess());
		nodeSql.append(nodeWhere.toString()); 
		List<WfmNode> curtNodes = db.findBySql(nodeSql.toString(), params.toArray());
		WfmNode curtNode = curtNodes.get(0);
		return curtNode;
	}
	
	/**  
	 * <p>Title: findNextNode</p>  
	 * <p>Description: 根据当前节点、当前节点流程获取下一个节点</p>  
	 * @param currentNode
	 * @param process
	 * @return  
	 */
	public static WfmNode findNextNode(WfmTask task) {
		
		WfmNode currentNode = findCurrentNode(task);
		int seqno = Integer.parseInt(currentNode.getSeqno());
		seqno=seqno+1;
		StringBuilder nodeSql=new StringBuilder("select m from WfmNode m ");
		StringBuilder nodeWhere=new StringBuilder("where m.wfmProcess=?1 and m.seqno=?2");
		List<Object> params=new ArrayList<>();
		params.clear();
		params.add(0,task.getWfmProcess());
		params.add(1,String.valueOf(seqno));
		nodeSql.append(nodeWhere.toString());
		List<WfmNode> nextNodes = db.findBySql(nodeSql.toString(),params.toArray());
		WfmNode nextNode = nextNodes.get(0);
		return nextNode;
	}
	
	/**  
	 * <p>Title: getNodeByTaskName</p>  
	 * <p>Description: 根据工作，回滚节点名获取相应的节点</p>  
	 * @param task
	 * @param rollNodeName  
	 */
	public static WfmNode getNodeByNodeName(WfmTask task,String rollbackNode) {
		
		StringBuilder nodeSql=new StringBuilder("select m from WfmNode m ");
		StringBuilder nodeWhere=new StringBuilder("where m.wfmProcess=?1 and m.name=?2");
		List<Object> params=new ArrayList<>();
		params.clear();
		params.add(0,task.getWfmProcess());
		params.add(1,rollbackNode);
		nodeSql.append(nodeWhere.toString());
		List<WfmNode> nodes = db.findBySql(nodeSql.toString(),params.toArray());
		WfmNode node = nodes.get(0);
		
		return node;
    }
	
	/**  
	 * <p>Title: getRoleByNode</p>  
	 * <p>Description: 获得当前节点角色的用户的微信公众号</p>  
	 * @param node
	 * @return  
	 */
	public static String getWxnosByNode(WfmNode node) {
		
		String assignee=null;
		List<Object> params=new ArrayList<>();
		
		if("task".equals(node.getNodeType())) {
			assignee=node.getAssignee();
		}
		params.add(0, assignee);
		
		StringBuilder roleSql=
				new StringBuilder("SELECT u.wxno FROM sys_users u " + 
				"LEFT JOIN sys_role_user ru ON u.ID=ru.USERID " + 
				"LEFT JOIN sys_roles r ON ru.ROLEID=r.ID ");
		StringBuilder roleWhere=
				new StringBuilder("WHERE r.ID=(SELECT r.ID FROM sys_roles r WHERE r.`NAME`=?1)");
		roleSql.append(roleWhere.toString());
		List<Object[]> roleUsers = db.findEntityByNSql(roleSql.toString(), params.toArray(), true);
		StringBuilder roleList=new StringBuilder();
		for (Object sysUser : roleUsers) {
			if(roleList.length()==0) {
				roleList.append(sysUser.toString());
			}else {
				roleList.append("|"+sysUser.toString());
			}
		}
		return roleList.toString();
	}
	
	/**  
	 * <p>Title: getWxnosByContract</p>  
	 * <p>Description: 根据合同获取内务、项目经理微信号</p>  
	 * @param bmeContract
	 * @return  
	 */
	public static String getWxnosByContract(BmeContract bmeContract) {
		
		String wxnos=null;
		String interior = bmeContract.getInterior();
		String pm = bmeContract.getPm();
		
		List<Object> interiors=new ArrayList<>();
		List<Object> pms=new ArrayList<>();
	
		interiors.add(0, interior);
		pms.add(0,pm);
		
		StringBuilder roleSql=
				new StringBuilder("SELECT u.wxno FROM sys_users u ");
		StringBuilder roleWhere=
				new StringBuilder("WHERE u.userno=?1");
		roleSql.append(roleWhere.toString());
		List<Object[]> roleUsers1 = db.findEntityByNSql(roleSql.toString(), interiors.toArray(), true);
		List<Object[]> roleUsers2 = db.findEntityByNSql(roleSql.toString(), pms.toArray(), true);
		wxnos=roleUsers1.get(0)+"|"+roleUsers2.get(0);
		return wxnos;
	}
	
	/**  
	 * <p>Title: getEnityByTask</p>  
	 * <p>Description: 根据当前任务获取不同的实体类</p>  
	 * @param task
	 * @return  
	 */
	public static Map<String,Object> getEnityByTask(WfmTask task) {
		
		String processName = task.getProcessName();
		Map<String,Object> map=new HashMap<>();
		if("wf_cgdd".equals(processName)) {
			BmePurchOrder purchOrder = new BmePurchOrder();
			purchOrder=db.findById(purchOrder.getClass(), task.getServiceNo());
			map.put(processName, purchOrder);
		}else if("wf_fhd".equals(processName)) {
			BmeReceipt receipt = new BmeReceipt();
			receipt=db.findById(receipt.getClass(), task.getServiceNo());
			map.put(processName, receipt);
		}else if("wf_ysdsh".equals(processName)) {
			BmeAcception acception = new BmeAcception();
			acception=db.findById(acception.getClass(), task.getServiceNo());
			map.put(processName, acception);
		}else if("wf_htbgsq".equals(processName)) {
			BmeContract contract = new BmeContract();
			contract=db.findById(contract.getClass(), task.getServiceNo());
			map.put(processName, contract);
		}else if("wf_htsh".equals(processName)) {
			BmeContract contract = new BmeContract();
			contract=db.findById(contract.getClass(), task.getServiceNo());
			map.put(processName, contract);
		}	
		
		return map;	
	}
	
	/**  
	 * <p>Title: sendMessageToAnyOne</p>  
	 * <p>Description: 把审核通过消息发送给内外、项目经理</p>  
	 * @param task
	 * @param wxnos
	 * @param message  
	 */
	public static void sendMessageToInterPm(WfmTask task) {
		
		Map<String, Object> map = getEnityByTask(task);
		Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> next = iterator.next();
			if("wf_cgdd".equals(next.getKey())) {
				BmePurchOrder purchOrder=(BmePurchOrder)next.getValue();
				BmeContract contract = purchOrder.getBmeContract();
				String wxnos = getWxnosByContract(contract);
				WeChatUtil.sendTextMessage(wxnos, "订单编号为："+purchOrder.getId()+"于"+new Data()+"已经通过审核！");
			}else if("wf_fhd".equals(next.getKey())) {
				BmeReceipt receipt=(BmeReceipt)next.getValue();
				BmeContract contract = receipt.getBmeContract();
				String wxnos = getWxnosByContract(contract);
				WeChatUtil.sendTextMessage(wxnos, "发货单号为："+receipt.getId()+"于"+new Data()+"已经通过审核！");
			}else if("wf_ysdsh".equals(next.getKey())) {
				BmeAcception acception=(BmeAcception)next.getValue();
				BmeContract contract = acception.getBmeContract();
				String wxnos = getWxnosByContract(contract);
				WeChatUtil.sendTextMessage(wxnos, "签收单号："+acception.getId()+"于"+new Data()+"已经通过审核！");
			}else if("wf_htbgsq".equals(next.getKey())) {
				BmeContract contract=(BmeContract)next.getValue();
				String wxnos = getWxnosByContract(contract);
				WeChatUtil.sendTextMessage(wxnos, "合同编号："+contract.getId()+"于"+new Data()+"已经通过审核！");
			}else if("wf_htsh".equals(next.getKey())) {
				//发送节点完成任务
				BmeContract contract=(BmeContract)next.getValue();
				String wxnos = getWxnosByContract(contract);
				WeChatUtil.sendTextMessage(wxnos, "合同编号："+contract.getId()+"于"+new Data()+"已经通过审核！");
				
				//下一个节点为end节点时，修改合同状态
				/*String name = nextNode.getName();
				if("end".equals(name)) {
					contract.setStatus("3");
					db.begin();
					db.update(contract);
					db.commit();
				}*/
			}
		}
	}
	
	/**  
	 * <p>Title: JudgeState</p>  
	 * <p>Description: 判断流程对象的状态</p>  
	 * @param task  
	 */
	public static boolean JudgeState(WfmTask task) {
		
		boolean flag=false;
		
		Map<String, Object> map = getEnityByTask(task);
		Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> next = iterator.next();
			if("wf_cgdd".equals(next.getKey())) {
				BmePurchOrder purchOrder=(BmePurchOrder)next.getValue();
				if("3".equals(purchOrder.getStatus())) {
					flag=true;
				}
			}else if("wf_fhd".equals(next.getKey())) {
				BmeReceipt receipt=(BmeReceipt)next.getValue();
				if("3".equals(receipt.getStatus())) {
					flag=true;
				}
			}else if("wf_ysdsh".equals(next.getKey())) {
				BmeAcception acception=(BmeAcception)next.getValue();
				if("3".equals(acception.getStatus())) {
					flag=true;
				}
			}else if("wf_htbgsq".equals(next.getKey())) {
				/*BmeContract contract=(BmeContract)next.getValue();
				if("3".equals(contract.getStatus())) {
					flag=true;
				}*/
			}else if("wf_htsh".equals(next.getKey())) {
				//发送节点完成任务
				BmeContract contract=(BmeContract)next.getValue();
				if("3".equals(contract.getStatus())) {
					flag=true;
				}
				
			}
		}
		return flag;
	}
	
	/**  
	 * <p>Title: sendWxMessage</p>  
	 * <p>Description: 向下一环节处理人发送微信消息</p>  
	 * @param task  
	 */
	public static void  sendWxMessageToNextNode(WfmTask task,String operator) {
		//获取下一个节点的
		WfmNode nextNode = findNextNode(task);
		//获取下一个节点的用户微信号
		String nodeUsersWx = getWxnosByNode(nextNode);
		
		Map<String, Object> map = getEnityByTask(task);
		Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> next = iterator.next();
			if("wf_cgdd".equals(next.getKey())) {
				BmePurchOrder purchOrder=(BmePurchOrder)next.getValue();
				
				//1、当订单走到供应商反馈提交流程,修改订单状态为"3"
				if("wf_inform1".equals(nextNode.getName())) {
					purchOrder.setStatus("3");
					db.beginTransaction();;
					db.update(purchOrder);
					db.commitTransaction();;
				}
				
				//2、给下一环节的人发送消息
				WeChatUtil.sendTextMessage(nodeUsersWx, "订单编号："+purchOrder.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",已完成审核，请你在我的工作中及时处理！");
			}else if("wf_fhd".equals(next.getKey())) {
				BmeReceipt receipt=(BmeReceipt)next.getValue();
				
				//1、获取发货单下的采购订单,已经发完货就把订单状态改为'0'
				BmePurchOrder bmePurchOrder = receipt.getBmePurchOrder();
				List<BmePurchDetail> bmePurchDetails = bmePurchOrder.getBmePurchDetails();
				int i=0;
				for (BmePurchDetail bp : bmePurchDetails) {
					if (bp.getSquantity().compareTo(bp.getMquantity())!=-1) {
						i++;
					}
				}
				
				if (bmePurchDetails.size()==i) {
					bmePurchOrder.setStatus("0");
					db.beginTransaction();
					db.update(bmePurchOrder);
					db.commitTransaction();
				}
				
				//2、现场签收物料，发货单状态改为'3'
				
				
				//3、给下一环节发送消息
				WeChatUtil.sendTextMessage(nodeUsersWx, "发货单编号："+receipt.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",审核已经完成，请你在我的工作中及时处理！");
			}else if("wf_ysdsh".equals(next.getKey())) {
				BmeAcception acception=(BmeAcception)next.getValue();
				
				//验收单审核通过，状态改为‘3’-已审核
				acception.setStatus("3");
				db.beginTransaction();
				db.update(acception);
				db.commitTransaction();
				
				//2、给下一个环节处理人发送消息
				WeChatUtil.sendTextMessage(nodeUsersWx, "签收单编号："+acception.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",审核已经完成，请你在我的工作中及时处理！");
				
			}else if("wf_htbgsq".equals(next.getKey())) {
				BmeContract contract=(BmeContract)next.getValue();
				WeChatUtil.sendTextMessage(nodeUsersWx, "合同编号："+contract.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",审核已经完成，请你在我的工作中及时处理！");
			}else if("wf_htsh".equals(next.getKey())) {
				//发送节点完成任务
				BmeContract contract=(BmeContract)next.getValue();
				WeChatUtil.sendTextMessage(nodeUsersWx, "合同编号："+contract.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",审核已经完成，请你在我的工作中及时处理！");
				
			}
			
			break;
		}
		
	}
	
	/**  
	 * <p>Title: sendWxMessageToAnyNode</p>  
	 * <p>Description: 根据工作流、回滚节点名称、处理人，把消息发送到相应回滚节点的处理人</p>  
	 * @param task
	 * @param rollbackNode
	 * @param operator  
	 */
	public static void sendWxMessageToAnyNode(WfmTask task,String rollbackNode,String operator) {
		
		WfmNode node = getNodeByNodeName(task, rollbackNode);
		String wxno = getWxnosByNode(node);
		
		Map<String, Object> map = getEnityByTask(task);
		Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> next = iterator.next();
			if("wf_cgdd".equals(next.getKey())) {
				BmePurchOrder purchOrder=(BmePurchOrder)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "订单编号："+purchOrder.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",已被退回，请你在我的工作中及时处理！");
			}else if("wf_fhd".equals(next.getKey())) {
				BmeReceipt receipt=(BmeReceipt)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "发货单编号："+receipt.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",已被退回，请你在我的工作中及时处理！");
			}else if("wf_ysdsh".equals(next.getKey())) {
				BmeAcception acception=(BmeAcception)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "签收单编号："+acception.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",已被退回，请你在我的工作中及时处理！");
			}else if("wf_htbgsq".equals(next.getKey())) {
				BmeContract contract=(BmeContract)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "合同编号："+contract.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",已被退回，请你在我的工作中及时处理！");
			}else if("wf_htsh".equals(next.getKey())) {
				//发送节点完成任务
				BmeContract contract=(BmeContract)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "合同编号："+contract.getId()+"处理环节："+findCurrentNode(task).getDisplayName()+
						"处理人："+operator+",已被退回，请你在我的工作中及时处理！");
				
				}
			}
		
	}
	
	/**  
	 * <p>Title: sendWxMessageToInitiators</p>  
	 * <p>Description: 通知流程发起人</p>  
	 * @param task
	 * @param operator
	 * @param roleName  
	 */
	public static void sendWxMessageToInitiators(WfmTask task,String operator,String roleName) {
		
		String wxno = WechatMessageUtils.getWxnosByRolename(roleName);
		
		Map<String, Object> map = getEnityByTask(task);
		Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, Object> next = iterator.next();
			if("wf_cgdd".equals(next.getKey())) {
				BmePurchOrder purchOrder=(BmePurchOrder)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "订单编号为："+purchOrder.getId()+
						"在采购订单流程："+findCurrentNode(task).getDisplayName()+"节点时被"+operator+"退回");
			}else if("wf_fhd".equals(next.getKey())) {
				BmeReceipt receipt=(BmeReceipt)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "发货单号为："+receipt.getId()+
						"在发货单流程："+findCurrentNode(task).getDisplayName()+"节点时被"+operator+"退回");
			}else if("wf_ysdsh".equals(next.getKey())) {
				BmeAcception acception=(BmeAcception)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "签收号为："+acception.getId()+
						"在验收单审批流程："+findCurrentNode(task).getDisplayName()+"节点时被"+operator+"退回");
			}else if("wf_htbgsq".equals(next.getKey())) {
				BmeContract contract=(BmeContract)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "合同编号为："+contract.getId()+
						"在合同变更申请流程："+findCurrentNode(task).getDisplayName()+"节点时被"+operator+"退回");
			}else if("wf_htsh".equals(next.getKey())) {
				//发送节点完成任务
				BmeContract contract=(BmeContract)next.getValue();
				WeChatUtil.sendTextMessage(wxno, "合同编号为："+contract.getId()+
						"在合同审核流程："+findCurrentNode(task).getDisplayName()+"节点时被"+operator+"退回");
				
				}
			}
	
	}
	
	/**  
     * <p>Title: getUsersByNode</p>  
     * <p>Description: 通过角色名获取相应的微信号</p>  
     * @param node
     * @return  
     */
    public static String getWxnosByRolename(String assignee) {
	
		List<Object> params=new ArrayList<>();
		params.add(0, assignee);
		
		StringBuilder roleSql=
				new StringBuilder("SELECT u.wxno FROM sys_users u " + 
				"LEFT JOIN sys_role_user ru ON u.ID=ru.USERID " + 
				"LEFT JOIN sys_roles r ON ru.ROLEID=r.ID ");
		StringBuilder roleWhere=
				new StringBuilder("WHERE r.ID=(SELECT r.ID FROM sys_roles r WHERE r.`NAME`=?1)");
		roleSql.append(roleWhere.toString());
		List<Object[]> roleUsers = db.findEntityByNSql(roleSql.toString(), params.toArray(), true);
		StringBuilder roleList=new StringBuilder();
		for (Object sysUser : roleUsers) {
			if(roleList.length()==0) {
				roleList.append(sysUser.toString());
			}else {
				roleList.append("|"+sysUser.toString());
			}
		}
		return roleList.toString();
	}
    
    
    
    
}
